import {View, Text, ScrollView} from "@tarojs/components";
import React, {useCallback, useEffect, useMemo, useRef, useState} from "react";
import AssetImage from "@/common/AssetImage";
import BottomButton from "@/components/bottom_button";
import DateUtils, {TimeSlot} from "@/utils/date_utils";
import Utils from "@/utils/common";
import LogUtils from "@/utils/log";

import Taro from "@tarojs/taro";
import {orderTimeApi} from "@/common/apis/home_datasource";
import ShowUtils from "@/utils/show_utils";
import {Tab, Tabs} from "@antmjs/vantui";
import './select_book_time.less'


definePageConfig({
  navigationBarTitleText: '选择预约时间'
})


export interface SelectBookTimeParams {
  projectId: any
  machineId: any
  slots: string[]
}

export default function SelectBookTime() {


  const [availability, setAvailability] = useState<string>()


  const [activeTabIndex, setActiveTabIndex] = useState(0);
  const [selectedSlots, setSelectedSlots] = useState<string[]>([]); // Store IDs of selected slots

  const dateTabs = useRef(DateUtils.getRecentDateTabs(DateUtils.getToday(), 7));

  // Get the ID of the currently selected date
  const activeDateId = useMemo(() => dateTabs.current[activeTabIndex].id, [activeTabIndex]);

  // Get the time slots for the currently selected date
  const currentSlots = useMemo(() => {
    if (activeDateId&&availability) {
      return DateUtils.generateTimeSlotsWithAvailabilityAndTimeCheck(activeDateId, DateUtils.transformStringToGroupedAvailability(availability));
    }
    return [];
  }, [activeDateId, availability]);

  // Handle tab change
  const handleTabChange = (event: any) => {
    setActiveTabIndex(event.detail.index);
    // setSelectedSlots([]); // Clear selection when changing date
  };

  // Handle time slot click
  const handleSlotClick = (slot: TimeSlot) => {
    if (slot.disabled) return; // Do nothing if disabled
    //说明不包含需要添加
    setSelectedSlots(prevSelected => {
      if (prevSelected.includes(slot.id)) {
        return prevSelected.filter(id => id !== slot.id);
      } else {
        //超过10个就提示最多5个小时
        return [...prevSelected, slot.id];
      }
    });
  };

  // Check if a slot is selected
  const isSlotSelected = (slotId: string) => selectedSlots.includes(slotId);
  ///不能选的背景色和字体颜色，能选的背景色和字体颜色，选上的背景色和字体颜色
  const getSlotStyle = (slot: TimeSlot) => {
    if (slot.disabled) {
      return {
        backgroundColor: AssetImage.bg,
        color: 'gray',
        textDecoration: 'line-through',
      };
    } else if (isSlotSelected(slot.id)) {
      return {
        backgroundColor: AssetImage.themeColorWithAlpha,
        color: AssetImage.themeColor,
      };
    } else {
      return {
        backgroundColor: AssetImage.bg,
        color: 'black',
      };
    }
  };

  const getTimes = useCallback(() => {
    if (bookInfo.current && bookInfo.current?.machineId) {
      orderTimeApi(bookInfo.current!.machineId.id).then((data) => {
        if(data){
          setAvailability('2025-05-17 16:00,2025-05-18 15:30,2025-05-19 15:00')
          if (!Utils.isEmpty(bookInfo.current?.slots)) {
            setSelectedSlots(bookInfo.current!.slots)
          }
        }
      })
    }
  }, []);

  const [, setRefresh] = useState({})
  const eventChannel = useRef<Taro.EventChannel | null>();
  const bookInfo = useRef<SelectBookTimeParams>();
  useEffect(() => {
    const instance = Utils.getI();
    eventChannel.current = Utils.getChannel(instance)
    const params = Utils.getParamsByRouter(instance)
    if (params && params.data) {
      const p = Utils.getObjectWithUrl<SelectBookTimeParams>(params.data)
      if (p) {
        bookInfo.current = {
          projectId: p.projectId,
          machineId: p.machineId,
          slots: p.slots
        }
        getTimes()
        LogUtils.info(p.slots);
      } else {
        setRefresh({})
      }
    }
  }, []);


  return (
    <View style={{display: 'flex', flexDirection: 'column', height: '100vh', padding: '20px', boxSizing: 'border-box'}}>
      {/* Header Placeholder */}
      {
        bookInfo.current ? <View>
          <Text>{bookInfo.current?.machineId.name}</Text>
          <View style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginTop: '10px'}}>
            <View>
              <Text>{bookInfo.current?.projectId.name}</Text>
              <Text style={{color: 'red'}}>{ShowUtils.getShowNote(bookInfo.current?.projectId.note)}</Text>
            </View>
            <Text style={{fontSize: '12px', color: 'gray'}}>1h起约</Text>
          </View>
        </View> : null
      }
      <Tabs
        swipeThreshold={3}
        active={activeTabIndex}
        onChange={handleTabChange}
        sticky={false} // Prevent tabs from sticking to top if page scrolls
      >
        {dateTabs.current.map((tab) => (
          <Tab key={tab.id} title={tab.title} titleStyle={{fontSize: '12px'}} />
        ))}
      </Tabs>
      <View style={{flex: 1, position: 'relative', overflow: 'hidden'}}>
        {/* Time Slot Grid */}
        <ScrollView className='gridLayout50ScrollView' scrollY style={{height: '100%'}}>
          {currentSlots.map((slot) => {
            const slotStyle = getSlotStyle(slot)
            return (
              <View style={{
                backgroundColor: slotStyle.backgroundColor,
                borderRadius: '10px',
                padding: '10px 0px',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}
                key={slot.id}
                onClick={() => handleSlotClick(slot)}
              >
                <Text style={{fontSize: '14px', color: slotStyle.color, textDecoration: slotStyle.textDecoration}}>
                  {slot.text}
                </Text>
              </View>
            )
          })}
        </ScrollView>
      </View>
      <BottomButton submitText={`选择完成 ${selectedSlots.length > 0 ? `(${selectedSlots.length / 2}h)` : ''}`}
        onSubmit={() => {
                      if (selectedSlots.length > 1 && eventChannel.current) {
                        Utils.emit(eventChannel.current, 'selectBookTime', selectedSlots)
                        Utils.navigateBack()
                      } else {
                        Utils.showErrorToast("1h起约")
                      }
                    }} margin='0px'
      />
    </View>
  );
}


